package com.example.gitdemo2;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    private SocketClient socketClient;
    private TextView receivedDataTextView;
    private EditText sendDataEditText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        receivedDataTextView = findViewById(R.id.received_data_text_view);
        sendDataEditText = findViewById(R.id.send_data_edit_text);


    }

    public void connect(View view) {
        // 假设开发板的 IP 地址为 "192.168.1.100" 和端口为 8888
        socketClient = new SocketClient("192.168.66.248", 8888);
        // 连接到服务器（开发板）
        socketClient.connect(new SocketClient.DataCallback() {
            @Override
            public void connectSuccess(boolean result) {
                String ans = result?"连接成功":"连接失败";
                runOnUiThread(()->Toast.makeText(MainActivity.this,ans,Toast.LENGTH_SHORT).show());
            }

            @Override
            public void onDataReceived(String data) {

            }
        });
        socketClient.receiveData(new SocketClient.DataCallback() {
            @Override
            public void connectSuccess(boolean result) {

            }

            @Override
            public void onDataReceived(String data) {
                runOnUiThread(()->Toast.makeText(MainActivity.this,data,Toast.LENGTH_SHORT).show());
                runOnUiThread(()->receivedDataTextView.setText(data));
            }
        });
        // 设置数据接收回调
//        socketClient.receiveData(data -> runOnUiThread(() -> receivedDataTextView.setText(data)));
    }

    // 发送数据到开发板
    public void sendData(View view) {
        String dataToSend = sendDataEditText.getText().toString();
        if (dataToSend.isEmpty()) {
            Toast.makeText(this, "请输入数据", Toast.LENGTH_SHORT).show();
        } else {
            socketClient.sendData(dataToSend);
            sendDataEditText.setText("");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        socketClient.close();
    }
}
